package com.biao.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biao.common.utils.HttpUtils;
import com.biao.common.utils.PageUtils;
import com.biao.common.utils.Query;
import com.biao.mall.member.dao.MemberDao;
import com.biao.mall.member.entity.MemberEntity;
import com.biao.mall.member.entity.MemberLevelEntity;
import com.biao.mall.member.exception.PhoneExistException;
import com.biao.mall.member.exception.UserNameExistException;
import com.biao.mall.member.service.MemberLevelService;
import com.biao.mall.member.service.MemberService;
import com.biao.mall.member.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        //设置默认用户等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        //检查数据是否唯一,为了让controller感知异常,异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        //密码加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        save(entity);
        //其它默认信息
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        LambdaQueryWrapper<MemberEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getMobile, phone);
        int count = count(wrapper);
        if (count > 0) {
            throw new PhoneExistException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        LambdaQueryWrapper<MemberEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getUsername, userName);
        int count = count(wrapper);
        if (count > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String username = vo.getLoginacct();
        LambdaQueryWrapper<MemberEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getUsername, username).or()
                .eq(MemberEntity::getMobile, username)
                .last("limit 1");
        MemberEntity member = getOne(wrapper);
        if (member != null) {
            //密码加密存储
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean b = passwordEncoder.matches(vo.getPassword(), member.getPassword());
            if (!b) {
                return null;
            }
            return member;
        }
        return null;
    }

    /**
     * @param vo gitee的code换取得access_token响应对应实体类
     * @return 返回数据库实体
     * @throws Exception 第一次就注册,否则就是登录
     */
    @Override
    public MemberEntity socialLogin(SocialUser vo) throws Exception {
        //①在gitee的每个用户都有一个唯一id,只要数据库中有这个唯一id就证明此账号此前登录过
        //使用请求返回唯一id
        Map<String, String> headersMap = new HashMap<>();
        Map<String, String> querysMap = new HashMap<>();
        querysMap.put("access_token",vo.getAccess_token());
//        querysMap.put("access_token", "7f82085da4414edd2b3469d0298364d8");
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "GET", headersMap, querysMap);
        if (!(response.getStatusLine().getStatusCode() ==200)) {
            throw new RuntimeException("查询不到gitee应用的用户信息");
        }
        String json = EntityUtils.toString(response.getEntity());
        GiteeUserInfoEntity giteeUserInfo = JSON.parseObject(json, GiteeUserInfoEntity.class);
        int giteeId = giteeUserInfo.getId();
        //判断giteeId是否存在
        LambdaQueryWrapper<MemberEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getGiteeId,giteeId).last("limit 1");
        MemberEntity memberEntity = getOne(wrapper);
        if (memberEntity==null){
            //注册
            MemberEntity registMember= new MemberEntity();
            MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
            registMember.setLevelId(levelEntity.getId());
            registMember.setNickname(giteeUserInfo.getName());
            registMember.setExpiresIn((long) vo.getExpires_in());
            registMember.setGiteeId(giteeId);
            registMember.setAccessToken(vo.getAccess_token());
            registMember.setEmail(giteeUserInfo.getEmail());
            save(registMember);
            return registMember;
        }

        MemberEntity updateMemberEntity = new MemberEntity();
        //更改数据库
        updateMemberEntity.setId(memberEntity.getId());
        updateMemberEntity.setAccessToken(vo.getAccess_token());
        updateMemberEntity.setExpiresIn((long) vo.getExpires_in());
        updateById(updateMemberEntity);
        //更改返回实体类
        memberEntity.setAccessToken(vo.getAccess_token());
        memberEntity.setExpiresIn((long) vo.getExpires_in());
        return memberEntity;
    }

    @Override
    public MemberEntity socialLoginWB(SocialUserWB socialUser) throws Exception {

        log.info("远程调用---");
        //①在gitee的每个用户都有一个唯一id,只要数据库中有这个唯一id就证明此账号此前登录过
        //使用请求返回唯一id
        Map<String, String> headersMap = new HashMap<>();
        Map<String, String> querysMap = new HashMap<>();
        querysMap.put("access_token",socialUser.getAccess_token());
        querysMap.put("uid",socialUser.getUid());
//        querysMap.put("access_token", "7f82085da4414edd2b3469d0298364d8");
        HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "GET", headersMap, querysMap);
        if (!(response.getStatusLine().getStatusCode() ==200)) {
            throw new RuntimeException("查询不到微博应用的用户信息");
        }

        String json = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSON.parseObject(json);

//        WBUserInfoEntity wbUserInfo = JSON.parseObject(json, WBUserInfoEntity.class);
        String wbId = jsonObject.getString("id");
        //判断giteeId是否存在
        LambdaQueryWrapper<MemberEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberEntity::getWbId,wbId).last("limit 1");
        MemberEntity memberEntity = getOne(wrapper);
        if (memberEntity==null){
            //注册
            MemberEntity registMember= new MemberEntity();
            MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
            registMember.setLevelId(levelEntity.getId());
            registMember.setNickname( jsonObject.getString("name"));
            registMember.setExpiresIn((long) socialUser.getExpires_in());
            registMember.setWbId(wbId);
            registMember.setAccessToken(socialUser.getAccess_token());
            save(registMember);
            return registMember;
        }

        MemberEntity updateMemberEntity = new MemberEntity();
        //更改数据库
        updateMemberEntity.setId(memberEntity.getId());
        updateMemberEntity.setAccessToken(socialUser.getAccess_token());
        updateMemberEntity.setExpiresIn((long) socialUser.getExpires_in());
        updateById(updateMemberEntity);
        //更改返回实体类
        memberEntity.setAccessToken(socialUser.getAccess_token());
        memberEntity.setExpiresIn((long) socialUser.getExpires_in());
        return memberEntity;
    }
}